// electron/service/ProcessService.ts
import CommandRepository from '../repository/CommandRepository';
import log from 'electron-log/main';

class ProcessService {
  async run(command: string, args: string[]): Promise<string> {
    return await CommandRepository.runCommand(command, args);
  }

  async startSearch(
    device: string,
    baudrates: string[],
    send: (msg: string) => void,
    onError?: (e: any) => void,
  ) {
    const command = 'uio_s';
    const args = ['--search', device, '-bs', ...baudrates];
    log.info(`Start search: ${command} ${args.join(' ')}`);
    return await CommandRepository.runCommandWithStream(
      command,
      args,
      send,
      onError,
    );
  }

  async stopSearch(send: (msg: string) => void) {
    const command = process.platform === 'win32' ? 'taskkill' : 'pkill';
    const args =
      process.platform === 'win32'
        ? ['/F', '/IM', 'uio_s.exe']
        : ['-f', 'uio_s'];
    log.info(`Stop search: ${command} ${args.join(' ')}`);
    return await CommandRepository.runCommandWithStream(command, args, send);
  }

  async startUpgrade(
    device: string,
    fileBufferBase64: string,
    baudrate = 1000000,
    servo_id = 0,
    send: (msg: string) => void,
  ) {
    const args = [
      device,
      '--fileBufferBase64',
      fileBufferBase64,
      '-s',
      String(servo_id),
      '-b',
      String(baudrate),
      '-r',
      '10',
      '-hs',
      '5',
      '-fr',
      '5',
      '-sr',
      '5',
      '-l',
      'DEBUG',
    ];
    return await CommandRepository.runCommandWithStream('uio_u', args, send);
  }
}

export default new ProcessService();
